import cv2


# https://blog.csdn.net/xiaofeixia002X/article/details/136224957
def test1():
    #
    img = cv2.imread('card.png')
    (h, w) = img.shape[:2]

    #
    center = (w // 2, h // 2)  # 旋转的中心点坐标
    angle = 45  # 旋转的角度
    scale = 1  # 图像缩放比例
    # 生成旋转矩阵，围绕图像中心旋转 angle°
    M = cv2.getRotationMatrix2D(center=center, angle=angle, scale=scale)
    print(type(M))

    # 仿射变换
    src = img  # 原始图像
    # M：变换矩阵，这里是由getRotationMatrix2D生成的旋转矩阵。
    dsize = (w, h)  # 输出图像的大小
    # flags：插值方法，通常使用INTER_LINEAR。
    # borderMode：边界像素模式。
    # borderValue：边界填充值，用于边界外的像素。
    # 仿射变换
    dst = cv2.warpAffine(src, M, dsize, flags=cv2.INTER_CUBIC, borderMode=100, borderValue=(0, 0, 255))

    #
    cv2.imshow('Contours', img)
    cv2.imshow('Contour1s', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def test2():
    #
    img = cv2.imread('card.png')
    (h, w) = img.shape[:2]

    #
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, 45, 1.0)
    # 2.2 新的宽高，radians(angle) 把角度转为弧度 sin(弧度)
    new_H = int(w * fabs(sin(radians(angle))) + h * fabs(cos(radians(angle))))
    new_W = int(h * fabs(sin(radians(angle))) + w * fabs(cos(radians(angle))))
    # 2.3 平移
    M[0, 2] += (new_W - w) / 2
    M[1, 2] += (new_H - h) / 2

    dst = cv2.warpAffine(img, M, (new_W, new_H), borderValue=(0, 0, 255))

    #
    cv2.imshow('Contours', img)
    cv2.imshow('Contour1s', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


if __name__ == '__main__':
    test1()
